package com.mareas.web.jsf.component;

import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.jsf.FacesContextUtils;

import com.mareas.web.model.Buque;
import com.mareas.web.service.BuqueService;
import com.mareas.web.service.GenericService;

@ManagedBean
@Scope("request")
@Component
@FacesConverter(forClass=Buque.class)
public class BuqueConverter implements Converter {

	@Autowired
	private GenericService genericService;
	
	public Object getAsObject(FacesContext facescontext,
			UIComponent uicomponent, String s) {
		Buque buque = null;
		if (getGenericService() == null)
		{
			BuqueService buqueService = (BuqueService) FacesContextUtils.getRequiredWebApplicationContext(facescontext).getBean("buqueService");
			//this.genericService = (GenericService) FacesContextUtils.getRequiredWebApplicationContext(facescontext).getBean("genericService");
			buque = (Buque) buqueService.get(Integer.parseInt(s));
			//buque = (Buque) getGenericService().get(Buque.class, Integer.parseInt(s));
			
			return buque;
		}
		
		buque = (Buque) getGenericService().get(Buque.class, Integer.parseInt(s));
		
		return buque;
	}

	public String getAsString(FacesContext facescontext,
			UIComponent uicomponent, Object obj) {
		if(obj == null)
			return null;
		return String.valueOf(((Buque) obj).getBuqueImo());
	}

	public GenericService getGenericService() {
		return genericService;
	}

	public void setGenericService(GenericService genericService) {
		this.genericService = genericService;
	}


}
